# -*- encoding: utf-8 -*-
'''
file       :main_api.py
Description: 编码主函数, 启动后作为api供人调用
Date       :2022/11/24 14:23:54
Author     :Josco
version    :python3.7.8
'''

from flask import Flask
from flask import request
import os
from pathlib import Path
from binary_to_pic import binary_to_pic
from generate_standard_pic import generate_standard_pic_method

app = Flask(__name__)

def scan_dir(dir_path):
    """递归扫描给定文件夹下的所有文件"""
    file_list = []
    for top, dirs, nondirs in os.walk(dir_path):
        for item in nondirs:
            file_list.append(os.path.join(top, item))
    return file_list

def deal_file_to_pic(file_list):
    """把传入文件夹下的所有文件/文件进行编码"""
    do_binary_to_pic = binary_to_pic()
    for file_name in file_list:
        # print("现在轮到：%s 编码了" % file_name)
        do_binary_to_pic.do_binary_to_pic(file_name)
    
@app.route('/post_file_name')
def post_file_name():
    file_name = request.values.get("file_name")
    print(file_name)
    try:
        
        my_file = Path(file_name)
        if my_file.is_dir():
            print("是个目录, 对目录中的所有文件进行操作")
            file_list = scan_dir(file_name)
            deal_file_to_pic(file_list)
            return file_list
        elif my_file.is_file():
            print("是个文件, 对该文件进行操作")
            deal_file_to_pic([file_name])
            return [file_name]
        else:
            print("啥也不是")
            return False
    except FileNotFoundError:
        # 不存在
        return False
    else:
        return scan_dir(file_name)

@app.route("/set_time")
def set_time():
    pass
    

if __name__ == '__main__':
    # 系统启动，进行编码部分初始化
    #（1）先进行标准化图像展示部分
    do_generate_standard_pic = generate_standard_pic_method()
    do_generate_standard_pic.generate_st_pic()
    app.run()


